package com.seventh.restaurant.service.Impl;

import com.seventh.restaurant.domain.Customer;
import com.seventh.restaurant.repository.CustomerRepository;
import com.seventh.restaurant.service.CustomerService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

    private final CustomerRepository customerRepository;

    public CustomerServiceImpl(CustomerRepository customerRepository) {
        this.customerRepository = customerRepository;
    }

    @Override
    public Customer insertNewCustomer(Customer customer) throws Exception {
        Customer customer1 = customerRepository.findByPhoneNumber(customer.getPhoneNumber());
        if (customer1!=null){
            Customer customer2 = new Customer();
            customer2.setName("该手机号码已经注册");
            return  customer2;
        }else {
            return customerRepository.save(customer);
        }
    }

    @Override
    public void deleteCustomer(Long id) {
       customerRepository.delete(id);
    }

    @Override
    public Customer updateCustomer(Customer customer) {
        Customer customer1 = customerRepository.findByPhoneNumber(customer.getPhoneNumber());
        customer1.setName(customer.getName());
        return customerRepository.save(customer1);
    }

    @Override
    public Customer findCustomer(String phoneNumber) throws Exception {
        Customer customer= customerRepository.findByPhoneNumber(phoneNumber);
        if (customer==null){
            throw new Exception("该顾客不存在，请注册！"+phoneNumber);
        }else {
            return customer;
        }
    }

    @Override
    public List<Customer> findAllCustomers() throws Exception {

        List<Customer> customers = customerRepository.findAll();
        if (customers.size()==0){
            throw new Exception("系统中还未有顾客");
        }else {

            return customers;
        }
    }
}
